package cn.muqingfeng.bbs.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ProgressBar;
import android.widget.Toast;
import cn.muqingfeng.api.RequestHelper;
import cn.muqingfeng.api.UriHelper;
import cn.muqingfeng.api.request.GsonRequest;
import cn.muqingfeng.api.to.Article2TO;
import cn.muqingfeng.api.to.Article3TO;
import cn.muqingfeng.api.to.ArticleList2TO;
import cn.muqingfeng.api.to.ArticleTO;
import cn.muqingfeng.api.to.BaseArticle2TO;
import cn.muqingfeng.api.to.UserTO;
import cn.muqingfeng.bbs.R;
import cn.muqingfeng.bbs.adapter.Article2Adapter;
import cn.muqingfeng.bbs.constants.Constants;
import cn.muqingfeng.bbs.ui.ArticleDetailActivity;
import cn.muqingfeng.bbs.ui.widget.xlistview.XListView;
import cn.muqingfeng.bbs.ui.widget.xlistview.XListView.IXListViewListener;
import cn.muqingfeng.util.AccountManager;
import cn.muqingfeng.util.ArticleCache;
import cn.muqingfeng.util.FavCache;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;

public class Article3ListFragment extends BaseFragment {
	private static final Object LOCK = new Object();
	private boolean isLoading = false;
	private View mContentView;
	private View mProgressLayout;
	private XListView mListLayout;
	private Article2Adapter mAdapter;
	private String mUrl;
	private Bundle mParams = null;
	private int mCurrrentPage = 1;
	private String mFid;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if (mContentView == null) {
			mContentView = View.inflate(inflater.getContext(), R.layout.article_list, null);
			mUrl = getArguments().getString(Constants.EXTRA_URL);
			mParams = getArguments().getBundle(Constants.EXTRA_BUNDLE);
			setupViews();
		}
		ViewGroup parentView = (ViewGroup) mContentView.getParent();
		if (parentView != null) {
			parentView.removeView(mContentView);
		}
		return mContentView;
	}

	private void setupViews() {
		mProgressLayout = mContentView.findViewById(R.id.progressLayout);
		mListLayout = (XListView) mContentView.findViewById(R.id.list_layout);
		mListLayout.setDivider(getResources().getDrawable(R.drawable.divider));
		mListLayout.setPullLoadEnable(true,
				mContext.getString(R.string.xlistview_footer_hint_normal));
		mListLayout.setPullRefreshEnable(false);
		mListLayout.setFooterDividersEnabled(false);
		mListLayout.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Object obj = parent.getItemAtPosition(position);
				if (obj != null && obj instanceof Article2TO) {
					Article2TO oldTO = (Article2TO) obj;
					Intent intent = new Intent(getActivity(), ArticleDetailActivity.class);
					ArticleTO to = new ArticleTO();
					to.setAuthor(oldTO.getAuthor());
					to.setAuthorId(oldTO.getAuthorId());
					to.setId(oldTO.getId());
					to.setPublishTime(oldTO.getPublishTime());
					to.setCover(oldTO.getCover());
					to.setReplyCount(oldTO.getReplyCount());
					to.setTitle(oldTO.getTitle());
					intent.putExtra(Constants.EXTRA_ARTICLE, to);
					intent.putExtra(Constants.EXTRA_FID, oldTO.getFid());
					startActivity(intent);
				}
			}
		});
		mListLayout.setXListViewListener(new IXListViewListener() {

			@Override
			public void onRefresh() {
				long time = ArticleCache.getLastRefreshTime(mContext, mUrl);
				mListLayout.setRefreshTime(time);
				loadFromNetwork(1);
			}

			@Override
			public void onLoadMore() {
				loadFromNetwork(mCurrrentPage + 1);
			}
		});
		mAdapter = new Article2Adapter(mContext);
		mListLayout.setAdapter(mAdapter);
		new LoadCacheNewsTask().execute();

	}

	class LoadCacheNewsTask extends AsyncTask<Void, Void, List<Article3TO>> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressLayout.setVisibility(View.VISIBLE);
		}

		@Override
		protected List<Article3TO> doInBackground(Void... params) {
			return null;
		}

		@Override
		protected void onPostExecute(List<Article3TO> result) {
			super.onPostExecute(result);
			if (result != null && !result.isEmpty()) {
				mAdapter.addNews(listA3ToA2(result));
				mAdapter.notifyDataSetChanged();
				mProgressLayout.setVisibility(View.GONE);
			}
			boolean noCache = result == null || result.isEmpty();
			long time = ArticleCache.getLastRefreshTime(mContext, mUrl);
			// 没有缓存或者过期
			if ((System.currentTimeMillis() - time > 5 * 60 * 1000) || noCache) {
				loadFromNetwork(1);
			}
		}

	}

	ArrayList<Article2TO> listA3ToA2(List<Article3TO> list) {
		ArrayList<Article2TO> arrays = new ArrayList<Article2TO>();
		if (list != null) {
			for (Article3TO to3 : list) {
				Article2TO to = new Article2TO();
				to.setAuthor(to3.getAuthor());
				to.setAuthorId(to3.getAuthorId());
				to.setCover(to3.getCover());
				to.setFid(to3.getFid());
				to.setId(to3.getId());
				to.setPublishTime(to3.getPublishTime());
				to.setReplyCount(to3.getReplyCount());
				to.setTitle(to3.getTitle());
				arrays.add(to);
			}
		}
		return arrays;
	}

	private void loadFromNetwork(final int page) {
		synchronized (LOCK) {
			if (isLoading)
				return;
			mCurrrentPage = page;
			isLoading = true;
			HashMap<String, String> params = new HashMap<String, String>();
			if (mParams != null) {
				for (String key : mParams.keySet()) {
					params.put(key, mParams.getString(key));
				}
			}
			params.put(UriHelper.PARAMS_PAGE_SIZE, String.valueOf(Constants.DEFAULT_PAGE_SIZE));
			params.put(UriHelper.PARAMS_PAGE_SIZE2, String.valueOf(Constants.DEFAULT_PAGE_SIZE));
			params.put(UriHelper.PARAMS_PAGE_NO, String.valueOf(page));
			GsonRequest<BaseArticle2TO> request = new GsonRequest<BaseArticle2TO>(Method.POST,
					mUrl, new Listener<BaseArticle2TO>() {

						@Override
						public void onResponse(BaseArticle2TO response) {
							isLoading = false;
							if (!isDetached()) {
								mListLayout.stopRefresh();
								mListLayout.stopLoadMore();
								ArticleList2TO listTO = response.getArticleListTO();
								if (listTO != null) {
									List<Article3TO> articles = listTO.getArticles3();
									if (page == 1) {
										mAdapter.clear();
									}
									if (articles != null && !articles.isEmpty()) {
										UserTO userTO = AccountManager.getUser(mContext);
										List<String> tids = new ArrayList<String>();
										for (Article3TO to : articles) {
											tids.add(to.getId());
										}
										FavCache.addFav(mContext, userTO.getUid(), tids);
									}
									mAdapter.addNews(listA3ToA2(articles));
									mAdapter.notifyDataSetChanged();
									if (articles.size() < Constants.DEFAULT_PAGE_SIZE) {
										mListLayout.setPullLoadEnable(false, null);
									} else {
										mListLayout.setPullLoadEnable(true, mContext
												.getString(R.string.xlistview_footer_hint_normal));
									}
								}
								mProgressLayout.setVisibility(View.GONE);
							}
						}
					}, new ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							isLoading = false;
							Toast.makeText(mContext, "请求失败，请重试!", Toast.LENGTH_SHORT).show();
							if (!isDetached()) {
								mListLayout.stopRefresh();
								mListLayout.stopLoadMore();
							}
						}
					}, params, BaseArticle2TO.class);
			request.setNeedLogin(true);
			RequestHelper.startRequest(mContext, request);
		}
	}
}
